/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * SerialConfigView.java
 *
 * Created on 12.Şub.2010, 16:55:01
 */
package org.testis.gui.mvc.view.testbed;

import org.testis.gui.mvc.controller.TestBedControllerList;
import org.testis.gui.mvc.controller.testbed.SerialConfigController;
import org.testis.gui.mvc.utilities.Validatable;
import org.testis.gui.mvc.utilities.ValidationUtils;
import org.testis.gui.mvc.view.AbstractViewPanel;
import org.testis.gui.mvc.view.AtofBaseDialog;
import org.testis.orm.testbed.refined.ConnectionTypeFactory;
import org.testis.orm.testbed.refined.ConnectionTypeRefined;
import org.testis.orm.testbed.refined.DirectSerialConfigFactory;
import org.testis.orm.testbed.refined.DirectSerialConfigRefined;
import org.testis.orm.testbed.refined.NetworkSerialConfigFactory;
import org.testis.orm.testbed.refined.NetworkSerialConfigRefined;
import org.testis.orm.testbed.refined.SerialConnectionRefined;
import java.awt.Frame;
import java.awt.event.WindowListener;
import java.beans.PropertyChangeEvent;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;

/**
 *
 * @author selcuk
 */
public class SerialConfigView extends AtofBaseDialog implements
        AbstractViewPanel, Validatable {

    private SerialConfigController m_controller;
    private boolean m_editMode;
    private int m_serialConnId;

    /** Creates new form SerialConfigView */
    public SerialConfigView(Frame owner, boolean modal, boolean editMode) {
        super(owner, modal);
        m_controller = TestBedControllerList.newInstance().getSerialConfigController();
        m_editMode = editMode;
        initComponents();
        setFrameIcon("images/testbed/" + SerialConnectionRefined.TYPE_NAME.toLowerCase(
                Locale.ENGLISH) + ".png");
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        nameTextField = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        connTypeComboBox = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        configComboBox = new javax.swing.JComboBox();
        saveButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(getWindowTitle());
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        jLabel1.setText("Name");

        jLabel2.setText("Type");

        connTypeComboBox.setModel(new DefaultComboBoxModel());
        connTypeComboBox.setEnabled(false);
        populateConnTypeComboBox();
        connTypeComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                connTypeComboBoxActionPerformed(evt);
            }
        });

        jLabel3.setText("Configuration");

        configComboBox.setModel(new DefaultComboBoxModel());
        configComboBox.setEnabled(false);

        saveButton.setText("Save");
        setDefaultButton(saveButton);
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(nameTextField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 258, Short.MAX_VALUE)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(configComboBox, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(connTypeComboBox, javax.swing.GroupLayout.Alignment.LEADING, 0, 168, Short.MAX_VALUE))))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(saveButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(cancelButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jLabel1)
                    .addComponent(nameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jLabel2)
                    .addComponent(connTypeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(jLabel3)
                    .addComponent(configComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cancelButton)
                    .addComponent(saveButton))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        if (!validateForm()) {
            return;
        }
        saveButton.setEnabled(false);

        String name = nameTextField.getText();
        int connTypeId = getSelectedConnTypeId();
        int configId = getSelectedConfigId();
        if (m_editMode) {
            m_controller.operationSaveSerialConn(m_serialConnId, name,
                    connTypeId,
                    configId);
        } else {
            m_controller.operationAddSerialConn(name, connTypeId, configId);
        }

        dispose();
}//GEN-LAST:event_saveButtonActionPerformed

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        WindowListener[] listeners = getWindowListeners();
        for (int i = 0; i < listeners.length; i++) {
            this.removeWindowListener(listeners[i]);
        }
        this.setVisible(false);
        this.setEnabled(false);
        m_controller.operationCloseWindow();
        this.dispose();
    }//GEN-LAST:event_formWindowClosed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        dispose();
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void connTypeComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connTypeComboBoxActionPerformed
        populateConfigComboBox(getSelectedConnTypeId());
    }//GEN-LAST:event_connTypeComboBoxActionPerformed

    @Override
    public void modelPropertyChange(PropertyChangeEvent evt) {
        if (evt.getPropertyName().equals(
                SerialConfigController.VISIBLE_PROPERTY)) {
            this.centerParent();
        } else if (evt.getPropertyName().equals(
                SerialConfigController.SERIAL_CONN_ID_PROPERTY)) {
            Integer val = (Integer) evt.getNewValue();
            m_serialConnId = val;
        } else if (evt.getPropertyName().equals(
                SerialConfigController.NAME_PROPERTY)) {
            String val = (String) evt.getNewValue();
            nameTextField.setText(val);
        } else if (evt.getPropertyName().equals(
                SerialConfigController.CONN_TYPE_ID_PROPERTY)) {
            Integer val = (Integer) evt.getNewValue();
            selectConnTypeCombobox(val);
        } else if (evt.getPropertyName().equals(
                SerialConfigController.CONFIG_ID_PROPERTY)) {
            Integer val = (Integer) evt.getNewValue();
            selectConfigCombobox(val);
        } else if (evt.getPropertyName().equals(
                SerialConfigController.ERROR_PROPERTY)) {
            String val = (String) evt.getNewValue();
            JOptionPane.showMessageDialog(
                    this,
                    val,
                    "Error Dialog",
                    JOptionPane.ERROR_MESSAGE);
        }
    }

    @Override
    public boolean validateForm() {
        boolean valid = true;
        StringBuilder builder = new StringBuilder();
        if (ValidationUtils.isEmpty(nameTextField.getText())) {
            builder.append("Name must not be empty.\n");
            valid = false;
        }

        if (!valid) {
            JOptionPane.showMessageDialog(null,
                    builder.toString(),
                    "Error",
                    JOptionPane.ERROR_MESSAGE);
        }
        return valid;
    }

    private void populateConnTypeComboBox() {
        connTypeComboBox.removeAllItems();
        List<ConnectionTypeRefined> li = ConnectionTypeFactory.newInstance().getConnectionTypeList();
        for (Iterator<ConnectionTypeRefined> it = li.iterator(); it.hasNext();) {
            ConnectionTypeRefined obj = it.next();
            connTypeComboBox.addItem(obj);
        }
    }

    private void selectConnTypeCombobox(int typeId) {
        DefaultComboBoxModel model = (DefaultComboBoxModel) connTypeComboBox.getModel();
        for (int i = 0; i < model.getSize(); i++) {
            ConnectionTypeRefined refined = (ConnectionTypeRefined) model.getElementAt(
                    i);
            if (refined != null && refined.getId() == typeId) {
                connTypeComboBox.setSelectedIndex(i);
                return;
            }
        }
    }

    private int getSelectedConnTypeId() {
        int result = 0;
        ConnectionTypeRefined obj = (ConnectionTypeRefined) connTypeComboBox.getSelectedItem();
        if (obj != null) {
            result = obj.getId();
        }
        return result;
    }

    private void populateConfigComboBox(int connTypeId) {
        configComboBox.removeAllItems();
        ConnectionTypeRefined connType = ConnectionTypeFactory.newInstance().getConnectionType(
                connTypeId);
        if (connType.getName().equals("direct")) {
            List<DirectSerialConfigRefined> configList = DirectSerialConfigFactory.newInstance().getConfigList();
            for (Iterator<DirectSerialConfigRefined> it = configList.iterator(); it.hasNext();) {
                configComboBox.addItem(it.next());
            }
        } else if (connType.getName().equals("network")) {
            List<NetworkSerialConfigRefined> configList = NetworkSerialConfigFactory.newInstance().getConfigList();
            for (Iterator<NetworkSerialConfigRefined> it = configList.iterator(); it.hasNext();) {
                configComboBox.addItem(it.next());
            }
        }
    }

    private void selectConfigCombobox(int configId) {
        DefaultComboBoxModel model = (DefaultComboBoxModel) configComboBox.getModel();
        for (int i = 0; i < model.getSize(); i++) {
            Object obj = model.getElementAt(i);
            if (obj instanceof DirectSerialConfigRefined) {
                DirectSerialConfigRefined configRefined = (DirectSerialConfigRefined) obj;
                if (configRefined.getId() == configId) {
                    configComboBox.setSelectedIndex(i);
                    return;
                }
            } else if (obj instanceof NetworkSerialConfigRefined) {
                NetworkSerialConfigRefined configRefined = (NetworkSerialConfigRefined) obj;
                if (configRefined.getId() == configId) {
                    configComboBox.setSelectedIndex(i);
                    return;
                }
            }
        }
    }

    private int getSelectedConfigId() {
        int result = 0;
        if (configComboBox.getSelectedItem() instanceof NetworkSerialConfigRefined) {
            NetworkSerialConfigRefined configRefined = (NetworkSerialConfigRefined) configComboBox.getSelectedItem();
            result = configRefined.getId();

        } else if (configComboBox.getSelectedItem() instanceof DirectSerialConfigRefined) {
            DirectSerialConfigRefined configRefined = (DirectSerialConfigRefined) configComboBox.getSelectedItem();
            result = configRefined.getId();
        }
        return result;
    }

    private String getWindowTitle() {
        if (m_editMode) {
            return new String("Edit Serial Connection");
        } else {
            return new String("Add New Serial Connection");
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelButton;
    private javax.swing.JComboBox configComboBox;
    private javax.swing.JComboBox connTypeComboBox;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JTextField nameTextField;
    private javax.swing.JButton saveButton;
    // End of variables declaration//GEN-END:variables
}
